package com.aiju.cash.ui.pay.util;

import android.text.TextUtils;

import com.aiju.bean.Discount;
import com.aiju.utils.L;
import com.aiju.utils.PriceUtil;
import com.aiju.utils.T;

import java.text.DecimalFormat;
import java.util.HashMap;

/**
 * @author: 佐为
 * @date: 2016-11-22 16:13
 * @version: V1.0
 * @Description: 收款键盘运算类
 */
public class AdditionMoney {

    public static final int BACK = 10; //后退
    public static final int POINT = 11; //小数点
    public static final int CLEAR = 12; //清理
    public static final int ADD = 13; //加
    public static final int PAY = 14; //付款
    public static final int ZERO = 15; //两个零

    static HashMap<Integer, String> keys = new HashMap<>();

    static {
        keys = new HashMap<>();
        keys.put(0, "0");
        keys.put(1, "1");
        keys.put(2, "2");
        keys.put(3, "3");
        keys.put(4, "4");
        keys.put(5, "5");
        keys.put(6, "6");
        keys.put(7, "7");
        keys.put(8, "8");
        keys.put(9, "9");
        keys.put(POINT, ".");
        keys.put(ADD, "+");
        keys.put(ZERO, "00");
    }

    /**
     * 当前输入的金额
     */
    private StringBuilder printMoney = new StringBuilder();

    /**
     * 当前输入的全部金额
     */
    private StringBuilder printAllMoney = new StringBuilder();

    /**
     * 输入总金额
     */
    private Double totalMoney = 0.00d;

    /**
     * 当前输入的金额
     */
    private Double inMoney = 0.00d;

    /**
     * 优惠金额
     */
    private Double favorable = 0.00d;

    /**
     * 应收金额
     */
    private Double receivable = 0.00d;

    /**
     * 优惠折扣
     */
    private Discount mDiscount;

    /**
     * 会员手机号
     */
    private String memberPhone;

    /**
     * 金额改变接口
     */
    private OnMoneyChange moneyChange;

    public void setMoneyChange(OnMoneyChange moneyChange) {
        this.moneyChange = moneyChange;
    }

    public interface OnMoneyChange {
        /**
         * @param favorable       优惠金额
         * @param printAllMoney   所有输入金额字符
         * @param totalMoney      总金额字符
         * @param receivableMoney 应收金额
         */
        void onMoneyChange(String favorable, String printAllMoney, String totalMoney, String receivableMoney);
    }

    public AdditionMoney() {

    }

    /**
     * 当收银键盘，按钮点击
     *
     * @param keyCode
     */
    public void onKeyDown(int keyCode) {
        switch (keyCode) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case ZERO:
            case POINT:
                calculateMoney(keyCode);
                break;
            case ADD:
                add();
                break;
            case BACK:
                back();
                break;
            case CLEAR:
                reset();
                break;
            case PAY:
                pay();
                break;
        }
    }

    /**
     * 重置
     */
    private void reset() {
        clearZero();
        checkDiscount();
        notifyMoneyChange();
    }

    /**
     * 计算钱
     *
     * @param number
     */
    private void calculateMoney(int number) {

        if (number == POINT) {
            if (printMoney.toString().contains(".") || printMoney.length() == 0) {
                return;
            }
        }
        if (printMoney.toString().equals("0")) {
            if (number != POINT) {
                return;
            }
        }
        if (checkTwoPoint()) {
            return;
        }

        totalMoney -= inMoney;
        printMoney.append(keys.get(number));
        printAllMoney.append(keys.get(number));
        inMoney = stringFormat(printMoney);
        totalMoney += inMoney;
        if (isGT20()) {
            T.ToastShort("总金额不能超过20万");
            back();
        }
        checkDiscount();
        notifyMoneyChange();
    }

    /**
     * 优惠券计算
     */
    private void checkDiscount() {
        if (mDiscount != null) {
            if (mDiscount.getType() == 1 || mDiscount.getType() == 4) {
                double v = Double.valueOf(PriceUtil.formatDouble(totalMoney * mDiscount.getDiscount()));
                favorable = totalMoney - v;
            } else {
                favorable = Double.valueOf(mDiscount.getValue());
            }
        }
    }

    /**
     * 设置优惠券
     */
    public void addDiscount(Discount discount) {
        this.mDiscount = discount;
        if (mDiscount != null) {
            if (mDiscount.getType() == 1 || mDiscount.getType() == 4) {
                double v = Double.valueOf(PriceUtil.formatDouble(totalMoney * mDiscount.getDiscount()));
                favorable = totalMoney - v;
            } else {
                favorable = Double.valueOf(mDiscount.getValue());
            }
        } else {
            favorable = 0d;
        }
        notifyMoneyChange();
    }

    /**
     * 删除优惠券
     */
    public void removeDiscount() {
        this.mDiscount = null;
        this.favorable = 0.00d;
        notifyMoneyChange();
    }

    /**
     * 检查输入两位小数点
     */
    private boolean checkTwoPoint() {
        if (TextUtils.isEmpty(printMoney)) {
            return false;
        }
        if (printMoney.indexOf(".") > 0) {
            int i = printMoney.lastIndexOf(".");
            return printMoney.length() - i == 3;
        } else {
            return false;
        }
    }

    /**
     * 加
     */
    private void add() {
        if (TextUtils.isEmpty(printMoney)) {
            return;
        }
        if (!TextUtils.isEmpty(printAllMoney) && isLastAdd(printAllMoney)) {
            return;
        }
        if (printMoney.toString().equals("0")) {
            back();
        } else {
            if (isHasAdd(printAllMoney)) {
                printAllMoney.delete(addIndex() + 1, printAllMoney.length());
                if (isHasPoint()) {
                    printAllMoney.append(formatDouble(printMoney.toString()));
                } else {
                    printAllMoney.append(printMoney.toString());
                }
            } else {
                clearPrintMoney(printAllMoney);
                if (isHasPoint()) {
                    printAllMoney.append(formatDouble(printMoney.toString()));
                } else {
                    printAllMoney.append(printMoney.toString());
                }
            }
        }
        inMoney = 0.00;
        printAllMoney.append("+");
        clearPrintMoney(printMoney);
        checkDiscount();
        notifyMoneyChange();
    }

    /**
     * 是否含小数
     *
     * @return
     */
    private boolean isHasPoint() {
        return printMoney.toString().contains(".");
    }

    /**
     * 首位“0”
     *
     * @return
     */
    private boolean isFirstZero() {
        return printMoney.indexOf("0") == 0;
    }

    /**
     * 付款
     */
    private void pay() {

    }

    /**
     * 后退
     */
    private void back() {
        if (TextUtils.isEmpty(printAllMoney)) {
            return;
        }
        if (!isHasAdd(printAllMoney)) {//输入的第一个值，没有"+"号
            printAllMoney.delete(printAllMoney.length() - 1, printAllMoney.length());

            if (TextUtils.isEmpty(printAllMoney)) {
                reset();
            } else {
                inMoney = Double.valueOf(formatDouble(printAllMoney.toString()));
                totalMoney = Double.valueOf(formatDouble(printAllMoney.toString()));
                clearPrintMoney(printMoney);
                printMoney.append(printAllMoney);
            }

        } else {
            if (!isLastAdd(printAllMoney)) {
                String lastMoney = printAllMoney.substring(addIndex(), printAllMoney.length());
                totalMoney = totalMoney - Double.valueOf(lastMoney);
            }
            printAllMoney.delete(addIndex(), printAllMoney.length());

            String lastMoney = printAllMoney.substring(addIndex() + 1, printAllMoney.length());
            clearPrintMoney(printMoney);
            printMoney.append(lastMoney);
        }

        L.d(printMoney.toString());
        checkDiscount();
        notifyMoneyChange();
    }

    /**
     * 大于20万
     *
     * @return
     */
    private boolean isGT20() {
        if (totalMoney > 200000 || stringFormat(printMoney) > 200000) {
            return true;
        }
        return false;
    }

    /**
     * 格式化显示字符
     */
    private Double stringFormat(StringBuilder builder) {
        return Double.valueOf(formatDouble(builder.toString()));
    }

    /**
     * 清零
     */
    private void clearZero() {
        clearPrintMoney(printMoney);
        clearPrintMoney(printAllMoney);
        totalMoney = 0.00;
        inMoney = 0.00;
    }

    /**
     * 通知回调
     */
    private void notifyMoneyChange() {
        if (moneyChange != null) {
            moneyChange.onMoneyChange(getFavorable(), getPrintAllMoney(), getTotalMoney(), getReceivableMoney());
        }
    }

    /**
     * 没有"+"
     */
    private boolean isHasAdd(StringBuilder builder) {
        return builder.indexOf("+") > 0;
    }

    /**
     * 最后一个字符"+"
     */
    private boolean isLastAdd(StringBuilder builder) {
        return builder.lastIndexOf("+") == builder.length() - 1;
    }

    /**
     * 字符"+"位置
     */
    private int addIndex() {
        return printAllMoney.lastIndexOf("+");
    }

    /**
     * 全部输入的金额字符
     *
     * @return
     */
    public String getPrintAllMoney() {
        return printAllMoney.toString();
    }

    /**
     * 总金额字符
     *
     * @return
     */
    public String getTotalMoney() {
        return formatDouble(totalMoney);
    }

    /**
     * 应收金额字符
     *
     * @return
     */
    public String getReceivableMoney() {
        return formatDouble(totalMoney - favorable);
    }

    /**
     * 优惠金额
     *
     * @return
     */
    public String getFavorable() {
        return formatDouble(favorable);
    }

    /**
     * 格式化钱（保留两位小数）
     *
     * @param money
     * @return
     */
    private String formatDouble(String money) {
        return formatDouble(Double.valueOf(money));
    }

    private String formatDouble(Double money) {
        DecimalFormat df = new DecimalFormat("#####0.00");
        return df.format(money);
    }

    /**
     * 清空当前输入金额字符
     */
    private void clearPrintMoney(StringBuilder builder) {
        builder.delete(0, builder.length());
    }

    public Discount getDiscount() {
        return mDiscount;
    }

    public String getMemberPhone() {
        return memberPhone;
    }

    public void setMemberPhone(String memberPhone) {
        this.memberPhone = memberPhone;
    }


}
